package com.open.ssm.common.aspectj;

import java.beans.PropertyDescriptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;

import com.open.ssm.common.annotation.Comment;
import com.open.ssm.common.utils.DateUtils;
import com.open.ssm.common.utils.DictUtils;
import com.open.ssm.common.utils.StringUtils;

public class ModiLogUtils<T> {
	
	/**
	 * 实体属性值比较
	 *
	 * @param pojo1
	 * @param pojo2
	 * @return String
	 */
    public String contrastObj(T pojo1, T pojo2) {
    	StringBuilder message = new StringBuilder();
        try {
            Class<? extends Object> clazz = pojo1.getClass();
            Field[] fields = pojo1.getClass().getDeclaredFields();
            int i = 1;
            for (Field field : fields) {
            	if("serialVersionUID".equals(field.getName())){
                    continue;
                }
            	
                PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
                Method readMethod = pd.getReadMethod();
                Annotation annotation = field.getAnnotation(Comment.class);
                if(annotation != null) {
                	Comment comment = (Comment)annotation;
                	Object o1 = readMethod.invoke(pojo1);
                	Object o2 = readMethod.invoke(pojo2);
                	String s1 = "";
                	String s2 = "";
                	if(o1 != null) {
                		if(o1 instanceof Date) {
                			try {
								s1 = DateUtils.parseDateToStr(comment.pattern(), (Date)o1);
							} catch (Exception e) {}
                		}else if(StringUtils.isNotBlank(comment.dictType())) {
                			s1 = DictUtils.getDictLabel(comment.dictType(), o1.toString());
                		}else {
                			s1=o1.toString();
                		}
                	}
                	if(o2!=null) {
                		if(o2 instanceof Date) {
                			try {
                				s2 = DateUtils.parseDateToStr(comment.pattern(), (Date)o2);
							} catch (Exception e) {}
                		}else if(StringUtils.isNotBlank(comment.dictType())) {
                			s1 = DictUtils.getDictLabel(comment.dictType(), o1.toString());
                		}else {
                			s2 = o2.toString();
                		}
                	}
                	if(!s1.equals(s2)) {
                		if(i!=1){
                			message.append(";<br/>");
                		}
                		message.append("字段名称："+comment.name()+"(旧值:"+s2+",新值:"+s1+")");
                		i++;
                	}
                } // end if(annotation != null)
            } // end for (Field field : fields)
        } catch (Exception e) {
        	e.printStackTrace();
        }
        return message != null ? message.toString() : "";
    }
}